/**
 * 
 */
package com.jushu.storbox.database;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

import com.jushu.storbox.ShareDriveApplication;
import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.constant.Constant;
import com.jushu.storbox.entities.FileFolderInfo;
import com.jushu.storbox.entities.FolderInfo;
import com.jushu.storbox.util.LogUtil;
import com.huawei.sharedrive.sdk.android.modelV2.response.FolderResponse;

public class ShareFolderDao extends BaseDao implements IShareFolderDao {
	public final static String TABLE_NAME = "tb_shard_folder_list";

	public final static String LOG_TAG = "ShareFolderDao";

	/**
	 * 
	 */
	public ShareFolderDao() {
	}

	@Override
	public void insertFolder(FolderResponse folderResponse,String defaultId) {
		try {
			ContentValues cv = new ContentValues();
			cv.put(IBaseDao.id, folderResponse.getId());
			cv.put(IBaseDao.file_name, folderResponse.getName());
			cv.put(IBaseDao.is_file, 0);
			cv.put(IBaseDao.owner_by, folderResponse.getOwnerBy());
			if(null != parent_folder_id){
				cv.put(IBaseDao.parent_folder_id, folderResponse.getParent());
			}else{
				cv.put(IBaseDao.parent_folder_id, defaultId);
			}
			cv.put(IBaseDao.file_size, folderResponse.getSize());
			cv.put(IBaseDao.server_ctime, folderResponse.getCreatedAt());
			cv.put(IBaseDao.server_mtime, folderResponse.getModifiedAt());
			cv.put(IBaseDao.last_refresh_time, 0);
			cv.put(IBaseDao.local_path, "");
			cv.put(IBaseDao.client_ctime, folderResponse.getContentCreatedAt());
			cv.put(IBaseDao.client_mtime, folderResponse.getContentModifiedAt());
			cv.put(IBaseDao.static_status, folderResponse.getStatus());
			cv.put(IBaseDao.trans_status, 0);
			cv.put(IBaseDao.trans_status_ref_cnt, 0);
			cv.put(IBaseDao.is_exist, 0);
			cv.put(IBaseDao.local_operation_time, Calendar.getInstance()
					.getTimeInMillis());
			cv.put(IBaseDao.local_last_modify_time, Calendar.getInstance()
					.getTimeInMillis());
			cv.put(IBaseDao.isencrypt, folderResponse.getIsEncrypt());
			cv.put(IBaseDao.isshare, folderResponse.getIsShare());
			cv.put(IBaseDao.isshare_link, folderResponse.getIsSharelink());
			cv.put(IBaseDao.isSync, 0);
			this.getDb().insert(TABLE_NAME, null, cv);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG,
					"insertFolder is fail:" + e.getLocalizedMessage());
		}
	}

	@Override
	public void updateFolder(FolderResponse folderInfoResponse,String defaultId) {
		try {
			String where = id + "=? and " + owner_by + "=?";
			String[] whereValue = { folderInfoResponse.getId(),
					folderInfoResponse.getOwnerBy() };
			ContentValues cv = new ContentValues();
			cv.put(IBaseDao.id, folderInfoResponse.getId());
			cv.put(IBaseDao.file_name, folderInfoResponse.getName());
			cv.put(IBaseDao.is_file, 0);
			cv.put(IBaseDao.owner_by, folderInfoResponse.getOwnerBy());
			if(null != IBaseDao.parent_folder_id){
				cv.put(IBaseDao.parent_folder_id, folderInfoResponse.getParent());
			}else{
				cv.put(IBaseDao.parent_folder_id, defaultId);
			}
			cv.put(IBaseDao.file_size, folderInfoResponse.getSize());
			cv.put(IBaseDao.server_ctime, folderInfoResponse.getCreatedAt());
			cv.put(IBaseDao.server_mtime, folderInfoResponse.getModifiedAt());
			cv.put(IBaseDao.local_path, "");
			cv.put(IBaseDao.client_ctime,
					folderInfoResponse.getContentCreatedAt());
			cv.put(IBaseDao.client_mtime,
					folderInfoResponse.getContentModifiedAt());
			cv.put(IBaseDao.last_refresh_time, 0);
			cv.put(IBaseDao.static_status, folderInfoResponse.getStatus());
			cv.put(IBaseDao.trans_status, 0);
			cv.put(IBaseDao.trans_status_ref_cnt, 0);
			cv.put(IBaseDao.is_exist, 0);
			cv.put(IBaseDao.local_operation_time, Calendar.getInstance()
					.getTimeInMillis());
			cv.put(IBaseDao.local_last_modify_time, Calendar.getInstance()
					.getTimeInMillis());
			cv.put(IBaseDao.isencrypt, folderInfoResponse.getIsEncrypt());
			cv.put(IBaseDao.isshare, folderInfoResponse.getIsShare());
			cv.put(IBaseDao.isSync, folderInfoResponse.getIsSync() ? 1 : 0);
			this.getDb().update(TABLE_NAME, cv, where, whereValue);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG,
					"updateFolder is fail:" + e.getLocalizedMessage());
		}
	}

	@Override
	public void updateFolder(FolderInfo folderInfo) {
		try {
			String where = id + "=? and " + owner_by + "=?";
			String[] whereValue = { folderInfo.getId(), folderInfo.getOwnerBy() };
			ContentValues cv = new ContentValues();
			cv.put(IBaseDao.id, folderInfo.getId());
			cv.put(IBaseDao.file_name, folderInfo.getName());
			cv.put(IBaseDao.is_file, 0);
			cv.put(IBaseDao.owner_by, folderInfo.getOwnerBy());
			cv.put(IBaseDao.parent_folder_id, folderInfo.getParent());
			cv.put(IBaseDao.file_size, folderInfo.getSize());
			cv.put(IBaseDao.server_ctime, folderInfo.getCreatedAt());
			cv.put(IBaseDao.server_mtime, folderInfo.getModifiedAt());
			cv.put(IBaseDao.local_path, "");
			cv.put(IBaseDao.client_ctime, folderInfo.getContentCreatedAt());
			cv.put(IBaseDao.client_mtime, folderInfo.getContentModifiedAt());
			cv.put(IBaseDao.last_refresh_time, folderInfo.getLastRefreshTime());
			if (null != folderInfo.getStatus())
				cv.put(IBaseDao.static_status, folderInfo.getStatus());
			else
				cv.put(IBaseDao.static_status, "");
			cv.put(IBaseDao.trans_status, 0);
			cv.put(IBaseDao.trans_status_ref_cnt, 0);
			cv.put(IBaseDao.is_exist, 0);
			cv.put(IBaseDao.local_operation_time, Calendar.getInstance()
					.getTimeInMillis());
			cv.put(IBaseDao.local_last_modify_time, Calendar.getInstance()
					.getTimeInMillis());
			if (null != folderInfo.getDescription())
				cv.put(IBaseDao.description, folderInfo.getDescription());
			else
				cv.put(IBaseDao.description, "");
			cv.put(IBaseDao.isencrypt, folderInfo.isEncrypt());
			cv.put(IBaseDao.isshare, folderInfo.isShare());
			cv.put(IBaseDao.isSync, folderInfo.isSync() ? 1 : 0);
			int ret = this.getDb().update(TABLE_NAME, cv, where, whereValue);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG,
					"updateFolder is fail:" + e.getLocalizedMessage());
		}
	}

	@Override
	public void insertOrUpdateFolder(Context context, FileFolderInfo folderInfo) {
		// TODO Auto-generated method stub
		try {
			String where = id + "=? and " + owner_by + "=?";
			String[] whereValue = { folderInfo.getId(), folderInfo.getOwnerBy() };
			ContentValues cv = new ContentValues();
			cv.put(IBaseDao.id, folderInfo.getId());
			cv.put(IBaseDao.file_name, folderInfo.getName());
			cv.put(IBaseDao.is_file, 0);
			cv.put(IBaseDao.owner_by, folderInfo.getOwnerBy());
			cv.put(IBaseDao.parent_folder_id, folderInfo.getParent());
			cv.put(IBaseDao.file_size, folderInfo.getSize());
			cv.put(IBaseDao.server_ctime, folderInfo.getCreatedAt());
			cv.put(IBaseDao.server_mtime, folderInfo.getModifiedAt());
			cv.put(IBaseDao.local_path, "");
			cv.put(IBaseDao.client_ctime, folderInfo.getContentCreatedAt());
			cv.put(IBaseDao.client_mtime, folderInfo.getContentModifiedAt());
			cv.put(IBaseDao.last_refresh_time, folderInfo.getLastRefreshTime());
			cv.put(IBaseDao.static_status, folderInfo.getStatus());
			cv.put(IBaseDao.trans_status, 0);
			cv.put(IBaseDao.trans_status_ref_cnt, 0);
			cv.put(IBaseDao.is_exist, 0);
			cv.put(IBaseDao.local_operation_time, Calendar.getInstance()
					.getTimeInMillis());
			cv.put(IBaseDao.local_last_modify_time, Calendar.getInstance()
					.getTimeInMillis());
			cv.put(IBaseDao.description, folderInfo.getDescription());
			FileFolderInfo folderinfors = DAOFactory
					.instance(context)
					.getShareFolderDao()
					.getFolderById(folderInfo.getId(),
							folderInfo.getOwnerBy());
			if (null == folderinfors) {
				this.getDb().insert(TABLE_NAME, null, cv);
			}else{
				this.getDb().update(TABLE_NAME, cv, where, whereValue);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG,
					"updateFolder is fail:" + e.getLocalizedMessage());
		}

	}

	@Override
	public List<FolderInfo> getFolderList(String folderId, String ownerBy) {
		List<FolderInfo> fileInfoList = new ArrayList<FolderInfo>();
		try {
			if (null != folderId) {
				Cursor cursor = this.getDb().rawQuery(
						"select * from " + TABLE_NAME
								+ " where parent_folder_id = ? and " + owner_by
								+ "=?", new String[] { folderId, ownerBy });
				if (false == cursor.moveToFirst()) {
					return fileInfoList;
				}
				do {
					FolderInfo folderInfo = new FolderInfo();
					folderInfo.fromCursor(cursor);
					fileInfoList.add(folderInfo);
				} while (cursor.moveToNext());
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG,
					"getFolderList is fail:" + e.getLocalizedMessage());
		}
		return fileInfoList;
	}

	@Override
	public void deleteFolder(String folderId, String ownerBy) {
		try {
			if (null != id) {
				this.getDb().execSQL(
						"delete from " + TABLE_NAME + " where id = ? and "
								+ owner_by + "=?",
						new String[] { folderId, ownerBy });
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG,
					"deleteFolder is fail:" + e.getLocalizedMessage());
		}
	}

	@Override
	public FolderInfo getFolderById(String folderId, String ownerBy) {
		FolderInfo folderInfo = null;
		try {
			if (null != folderId) {
				Cursor cursor = this.getDb().query(
						TABLE_NAME,
						new String[] { FIELD_ID, id, file_name, owner_by,
								is_file, parent_folder_id, file_size,
								server_ctime, server_mtime, last_refresh_time,
								local_path, client_ctime, client_mtime,
								static_status, trans_status,
								trans_status_ref_cnt, is_exist,
								local_operation_time, local_last_modify_time,
								description, isencrypt, isshare, isshare_link,
								isSync }, id + " = ? and " + owner_by + "=?",
						new String[] { folderId, ownerBy }, null, null,
						" id desc");
				if (cursor.moveToFirst()) {
					folderInfo = new FolderInfo();
					folderInfo.fromCursor(cursor);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG,
					"getFolderById is fail:" + e.getLocalizedMessage());
		}
		return folderInfo;
	}

	@Override
	public void updateLocalPath(String folderId, String localPath,
			String ownerBy) {
		try {
			if (null != folderId) {
				this.getDb().execSQL(
						"update  " + TABLE_NAME + " set " + IBaseDao.local_path
								+ "=? where id = ? and " + owner_by + "=?",
						new String[] { localPath, folderId, ownerBy });
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG,
					"updateLocalPath is fail:" + e.getLocalizedMessage());
		}
	}

	@Override
	public void updateTransStatus(int status, String folderId, String ownerBy) {
		try {
			String where = id + "=? and " + owner_by + "=?";
			String[] whereValue = { folderId, ownerBy };
			ContentValues cv = new ContentValues();
			cv.put(IBaseDao.trans_status, status);
			this.getDb().update(TABLE_NAME, cv, where, whereValue);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG,
					"updateTransStatus is fail:" + e.getLocalizedMessage());
		}

	}

	@Override
	public int updateSyncStatuc(int syncStatus, String folderId, String ownerBy) {
		try {
			String where = id + " = ? and " + owner_by + " = ?";
			String[] whereValue = { folderId, ownerBy };
			ContentValues cv = new ContentValues();
			cv.put(isSync, syncStatus);
			return this.getDb().update(TABLE_NAME, cv, where, whereValue);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG,
					"updateSyncStatuc is fail:" + e.getLocalizedMessage());
		}
		return -1;
	}

	@Override
	public void updateLastRefreshTime(String shareOwnerId, String folderId,
			long lastRefreshTime) {
		try {
			if (null != folderId) {
				this.getDb().execSQL(
						"update  " + TABLE_NAME + " set "
								+ IBaseDao.last_refresh_time
								+ "=? where id = ? and " + owner_by + "=?",
						new String[] { "" + lastRefreshTime, folderId,
								shareOwnerId });
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG,
					"updateLastRefreshTime is fail:" + e.getLocalizedMessage());
		}
	}

	@Override
	public long getLastRefreshTime(String shareOwnerId, String folderId) {
		long lastRefreshTime = 0;
		try {
			if (null != folderId) {
				Cursor cursor = this.getDb().rawQuery(
						"select * from  " + TABLE_NAME + " where id = ? and "
								+ owner_by + "=?",
						new String[] { folderId, shareOwnerId });
				if (cursor.moveToFirst()) {
					lastRefreshTime = cursor.getLong(cursor
							.getColumnIndex(IBaseDao.last_refresh_time));
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG,
					"getLastRefreshTime is fail:" + e.getLocalizedMessage());
		}
		return lastRefreshTime;
	}

	public long getLastUpdateTime(String folderId) {
		long lastUpdateTime = 0;
		try {
			if (null != folderId) {
				Cursor cursor = this.getDb().rawQuery(
						"select * from  " + TABLE_NAME + " where id = ?",
						new String[] { folderId });
				if (cursor.moveToFirst()) {
					lastUpdateTime = cursor.getLong(cursor
							.getColumnIndex(IBaseDao.local_last_modify_time));
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG,
					"getLastUpdateTime is fail:" + e.getLocalizedMessage());
		}
		return lastUpdateTime;
	}

	public void updateLastUpdateTime(String folderId) {
		try {
			if (null != folderId) {
				this.getDb().execSQL(
						"update  " + TABLE_NAME + " set "
								+ IBaseDao.local_last_modify_time
								+ "=? where id = ?",
						new String[] {
								"" + Calendar.getInstance().getTimeInMillis(),
								folderId });
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG,
					"updateLastUpdateTime is fail:" + e.getLocalizedMessage());
		}
	}

	/**
	 * 
	 * @param context
	 * @param name
	 */
	public void renameFolder(String name, String folderID, String ownerBy) {
		try {
			if (null != folderID) {
				this.getDb().execSQL(
						"update " + TABLE_NAME + " set " + IBaseDao.file_name
								+ " = ? where id = ? and " + owner_by + "=?",
						new String[] { name, folderID, ownerBy });
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG,
					"renameFolder is fail:" + e.getLocalizedMessage());
		}
	}

	/**
	 * @param context
	 * @param parentID
	 * @param FolderID
	 */
	public void moveFolder(String parentID, String folderID, String ownerBy) {
		try {
			if (null != folderID) {
				this.getDb().execSQL(
						"update " + TABLE_NAME + " set "
								+ IBaseDao.parent_folder_id
								+ " = ? where id = ? and " + owner_by + "=?",
						new String[] { parentID, folderID, ownerBy });
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "moveFolder is fail:" + e.getLocalizedMessage());
		}
	}

	@Override
	public void deleteAll() {
		// TODO Auto-generated method stub
		try {
			this.getDb().delete(TABLE_NAME, null, null);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "deleteAll is fail:" + e.getLocalizedMessage());
		}
	}

	@Override
	public List<FolderInfo> getFolderListPage(int flag, String folderId) {
		if (null != folderId) {
			int number = ClientConfig.CLOUD_COUNT_PER_PAGE;
			int count = ShareDriveApplication.getInstance()
					.getMyCloudDrivePage() * number;
			if (Constant.SHARED_GET_FILE_LIST_STATE == flag) {
				number = ClientConfig.SHARED_COUNT_PER_PAGE;//
				count = ShareDriveApplication.getInstance().getMySharePage()
						* number;
			}

			List<FolderInfo> fileInfoList = new ArrayList<FolderInfo>();
			try {
				if (null != folderId) {

					Cursor cursor = this
							.getDb()
							.rawQuery(
									"select * from "
											+ TABLE_NAME
											+ " where parent_folder_id = ? Order by server_mtime desc"
											+ " limit ?" + " offset ?",
									new String[] { folderId,
											String.valueOf(number),
											String.valueOf(count) });
					if (false == cursor.moveToFirst()) {
						return fileInfoList;
					}
					do {
						FolderInfo folderInfo = new FolderInfo();
						folderInfo.fromCursor(cursor);
						fileInfoList.add(folderInfo);
					} while (cursor.moveToNext());
				}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				LogUtil.e(LOG_TAG,
						"getFolderListPage is fail:" + e.getLocalizedMessage());
			}
			return fileInfoList;
		} else {
			LogUtil.e(LOG_TAG, "folderId is null");
		}
		return null;
	}

	@Override
	public void cleanCatch(){
		try {
			String currentUser = ShareDriveApplication.getInstance().getWnerID();
			if(currentUser == null || currentUser.equals("")){
				return ;
			}
			ContentValues values = new ContentValues();
			values.put(IBaseDao.local_path, "");
			values.put(IBaseDao.trans_status, Constant.DOWNLOAD_NON_UPDATE_DB);
			values.put(IBaseDao.isSync, Constant.DOWNLOAD_STATUS_NOCACHE_DB);
			String whereClause = IBaseDao.owner_by + " = ?";
			String[] whereArgs = {currentUser};
			this.getDb().update(TABLE_NAME, values, whereClause, whereArgs);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "cleanCatch is fail:" + e.getLocalizedMessage());
		}
	}
}
